package response

import (
  "github.com/gin-gonic/gin"
  "net/http"
  "reflect"
)

type Response struct {
  Code int         `json:"code"`
  Data interface{} `json:"data,omitempty"`
  Msg  string      `json:"message"`
}

type MsgResponse struct {
  Code int         `json:"code"`
  Msg  string      `json:"message"`
}

const (
  ERROR   = 40000
  SUCCESS = 20000
)

func Result(code int, data interface{}, msg string, c *gin.Context) {
  // 开始时间
  value := reflect.ValueOf(data)
  if value.IsZero() {
    c.JSON(http.StatusOK, MsgResponse{
      Code: code,
      Msg:  msg,
    })
  } else {
    c.JSON(http.StatusOK, Response{
      code,
      data,
      msg,
    })
  }
}

func Ok(c *gin.Context) {
  Result(SUCCESS, "", "操作成功", c)
}

func OkWithMessage(message string, c *gin.Context) {
  Result(SUCCESS, "", message, c)
}

func OkWithData(data interface{}, c *gin.Context) {
  Result(SUCCESS, data, "操作成功", c)
}

func OkWithDetailed(data interface{}, message string, c *gin.Context) {
  Result(SUCCESS, data, message, c)
}

func Fail(c *gin.Context) {
  Result(ERROR, "", "操作失败", c)
}

func FailWithMessage(message string, c *gin.Context) {
  Result(ERROR, "", message, c)
}

func FailWithDetailed(data interface{}, message string, c *gin.Context) {
  Result(ERROR, data, message, c)
}
